<?php
/**
 * Created by PhpStorm.
 * User: jason
 * Date: 2017/10/12
 * Time: 16:55
 */

namespace Home\Controller;


use Common\Util\HttpClient;
use Home\Service\UserService;
use Think\Controller;

class LoginController extends Controller
{
    public function index()
    {
        $appId = C('WECHATLOGIN.appId');
        $redirectUrl = urlencode('https://www.dscore.cn/home/login/callback');

        //todo state参数
        $url = 'https://open.weixin.qq.com/connect/qrconnect?appid='.$appId.'&redirect_uri='.$redirectUrl.'&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect';
        return redirect($url);
    }

    /*
     * 微信用户授权回调方法
     */
    public function callback()
    {
        $code = I('code');
        $state = I('state');
        $appId = C('WECHATLOGIN.appId');
        $appSecret = C('WECHATLOGIN.appSecret');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$appSecret.'&code='.$code.'&grant_type=authorization_code';
        //获取access_token和union_id;
        $returnInfo = json_decode(HttpClient::get($url), true);

        //获取用户信息并更新记录
        $service = new UserService();
        $userInfo = $service->addUser($returnInfo);

        //查询是否是会员
        $map = [
            'user_id' => $userInfo['uid'],
            'amount' => ['gt', 0]
        ];
        $member = M('UserCoinWallet')->where($map)->find();
        if ($member) {
            $userInfo['is_member'] = 1;
        } else {
            $userInfo['is_member'] = 0;
        }
        //保存session
        session('user', $userInfo);

        $this->redirect('/home/index');
    }

    /*
     * 验证是否登录
     */
    public function check()
    {
        $user = session('user');
        if (empty($user)) {
            $return['code'] = 10001;
            $return['msg'] = '请先登录';
            $this->ajaxReturn($return);
        } else {
            $return['code'] = 200;
            $return['msg'] = '验证成功';
            $this->ajaxReturn($return);
        }
    }

    public function loginOut()
    {
        session('user', null);
        $this->redirect('/home/index');
    }


}